package com.bk.controller;

import com.bk.utils.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    // 服务器存储位置
    private static final String PARENT_PATH = "D:\\IDEA\\project\\bk\\src\\main\\resources\\static\\upload\\";

    //本地访问路径
    private static final String LOCAL_PATH = "http://localhost:8080/upload/";

    @RequestMapping("/upload")
    @Valid
    public Result upload(@RequestParam @NotNull(message = "请上传文件") MultipartFile file) throws IOException {
        String type = file.getContentType(); // 获取文件类型
        long size = file.getSize(); // 获取文件大小
        if (size > 1024 * 1024 * 10) {
            return Result.error("401", "文件大小不能超过10M");
        }
        if (type != null) {
            type = type.substring(type.lastIndexOf("/") + 1);
        }
//        if ("image/jpeg".equals(type)) {
//            type = ".jpg";
//        }
        // 构建uuid作为唯一标识
        String saveFileName = UUID.randomUUID() + "." + type;
        File uploadFile = new File(PARENT_PATH + saveFileName);
        // 判断父级目录是否存在，不存在则创建
        File parentFile = uploadFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        // 文件存储到磁盘上
        file.transferTo(uploadFile);
        String abbreviationsFileName = UUID.randomUUID() + "." + type;
        // 使用 Thumbnails 进行缩放和保存指定大小的图片
        Thumbnails.of(uploadFile)
                .size(400, 400) // 指定大小
                .outputFormat("jpg") // 输出格式为jpg
                .toFile(new File(PARENT_PATH + abbreviationsFileName)); // 保存缩放后的图片
        uploadFile.delete();
        // 返回对外访问路径
        return Result.success(LOCAL_PATH + abbreviationsFileName);
    }

    // 文件下载接口
    @RequestMapping("/{saveFileName}")
    public void download(@PathVariable String saveFileName, HttpServletResponse response) throws IOException {
        // 通过response将数据输出
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(PARENT_PATH + saveFileName);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(saveFileName, StandardCharsets.UTF_8));
        response.setContentType("application/octet-stream");
        // 创建文件输入流
        FileInputStream fis = new FileInputStream(uploadFile);
        // 读取文件的字节流
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = fis.read(buf)) != -1) {
            // 边读边写
            os.write(buf, 0, readLen);
        }
        os.flush();
        os.close();
    }


}
